/*
 * @Author: wjc
 * @Date: 2025-02-13 14:52:31
 * @LastEditors: wjc
 * @LastEditTime: 2025-10-28 10:26:02
 * @Description:
 */
import type { RouteRecordRaw } from 'vue-router'

import { formatAction } from '#/utils/check-action'
import { resolve } from 'path-browserify'

/**
 * Use meta.actions to determine if the current user has permission
 * @param actions
 * @param route
 */
function hasPermission(actions: string[], route: RouteRecordRaw) {
  return route.meta && route.meta.actions
    ? route.meta.actions.some((action) => actions.includes(formatAction(action)))
    : true
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param actions
 */
export function filterAsyncRoutes(routes: RouteRecordRaw[], actions: string[]): RouteRecordRaw[] {
  const res: RouteRecordRaw[] = []
  routes.forEach((route) => {
    const tmp = { ...route }
    if (hasPermission(actions, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, actions)
      }

      // 如果当前 nav 不带跳转，并且 children > 0 才加入路由
      if (tmp.redirect === 'noRedirect') {
        if (tmp.children && tmp.children.length > 0) {
          res.push(tmp)
        }
      } else {
        res.push(tmp)
      }
    }
  })

  return res
}

export function resolvePath(basePath: string, path: string) {
  return resolve(basePath, path)
}
